package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2017/12/4 11:57
 * 邮箱：lanbuhan@163.com
 * 功能：注册
 */
@ContentView(R.layout.regis)
public class ReigsActivity extends BaseActivity implements TextWatcher {
    private String botoom_title = "注册登录内蒙古文化云即表示您同意«<font color='#00a3ea'>用户协议</font>»";
    private String REG_NORMAL = "0" ;
    private String REG_OTHER = "1" ;
    private String reg_type = REG_NORMAL;//默认普通注册
    private int VERIFICATIONCONTENTSTR_SIZE = 6;//验证码的长度
    int i = 60;

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.submit)
    TextView submit;

    @ViewInject(R.id.verification_code)
    TextView verification_code;

    @ViewInject(R.id.regis_botton)
    TextView regis_botton;

    @ViewInject(R.id.phone)
    EditText phone;

    @ViewInject(R.id.code)
    EditText code;

    @ViewInject(R.id.one_pass)
    EditText one_pass;

    String appInfo;

    String format;

    @Event(value = {R.id.back,R.id.regis_botton,R.id.verification_code,R.id.submit})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.regis_botton:
                String result = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");
                if(isRequestStr(result)){
                    String url = JSONTool.jsonDefaluTranString(result,AppHttpKey.USER_AGREEMENT);
                    TransformController.transformControllerModel(QXApplication.getContext(),
                            HtmlActivity.class,
                            new Base(url,getString(R.string.info_msg)));
                }
                break;
            case R.id.verification_code:
                //获取验证码
                String phoneNums = phone.getText().toString();
                // 1. 通过规则判断手机号
                if (!judgePhoneNums(phoneNums)) {
                    return;
                }
                // 2.发送短信验证码
                updateVerification(phoneNums);
                // 3.倒计时
                verification_code.setClickable(false);
                verification_code.setText("重新发送("+i+")");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-9);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-8);
                    }
                }).start();
                break;
            case R.id.submit:
                String phoneStr = getEditToString(phone);
                String codeStr = getEditToString(code);
                String onePassStr = getEditToString(one_pass);

                int length = onePassStr.length();
                if(length<6 || length>16){
                    PromptManager.showToast(R.string.password_number_hint);
                    return;
                }

                if(!CommonUtil.isPassNO(onePassStr)){
                    PromptManager.showToast(R.string.pass_format_hint);
                    return;
                }

                if(isRequestStr(phoneStr)&&isRequestStr(codeStr)&&isRequestStr(onePassStr)){
                    if(!judgePhoneNums(phoneStr)){
                        //不合法手机号码
                        PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
                    }else{
                        submit.setEnabled(false);
                        mapKeys.put(AppHttpKey.MOBILE,phoneStr);
                        mapKeys.put(AppHttpKey.PASSWORD,onePassStr);
                        mapKeys.put(AppHttpKey.MOBILE_CODE,codeStr);
//                        mapKeys.put(AppHttpKey.REG_TYPE,reg_type);

                        AppHttpRequest.appQuitState(ApplicationConfig.SAVE_REGISTER,
                                mapKeys,
                                new AppHttpRequest.OnAppHttpListener() {
                                    @Override
                                    public void onAppHttpState(boolean isState, String result) {
                                        submit.setEnabled(true);
                                        if(isState){
                                            PromptManager.showToast(R.string.register_success);
//                                            TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                                            ReigsActivity.this.finish();
                                        }else{
                                            PromptManager.showToast(JSONTool.errorHint(result));
                                        }
                                    }
                                });
                    }
                }else{
                    PromptManager.showToast(R.string.phone_password_no);
                }
                break;
        }
    }



    private void updateVerification(String phoneNums){
        if (!judgePhoneNums(phoneNums)) {
            PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
            return;
        }

        mapKeys.put(AppHttpKey.MOBILE,phoneNums);
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.SEND_SMS,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            PromptManager.showToast(JSONTool.errorHint(result));
                        }
                    }
                });
    }


    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (CommonUtil.isMatchLength(phoneNums, 11)
                && CommonUtil.isMobileFormatNO(format,phoneNums)) {
            return true;
        }
        PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
        return false;
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                verification_code.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                verification_code.setText("获取验证码");
                verification_code.setClickable(true);
                i = 60;
            }
        }
    };



    @Override
    public void initSucessView() {}
    @Override
    public void initData(Bundle savedInstanceState) {
        appInfo();
    }

    private void appInfo(){
        appInfo = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");

        if(!CommonUtil.isRequestStr(appInfo)){
            AppHttpRequest.httpAppInfo(new AppHttpRequest.OnAppHttpListener() {
                @Override
                public void onAppHttpState(boolean isState, String result) {
                    if(isState){
                        appInfo = result;
                    }
                }
            });
        }

        format = JSONTool.requestJSONfindName(JSONTool.jsonDefaluTranString(appInfo,JSONTool.Enum.MOBILE_FORMAT),
                JSONTool.Enum.FORMAT);

        SystemPrintl.systemPrintl("我的手机对比正则表达式--->>"+format);
    }

    @Override
    public void initViewHandler() {
        textViewHTTPText(regis_botton,botoom_title);
        phone.addTextChangedListener(this);
        code.addTextChangedListener(this);
        one_pass.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//        submit.setEnabled(false);
//        submit.setBackgroundResource(R.drawable.ash_btn_frame);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String phoneStr = getEditToString(phone);
        String codeStr = getEditToString(code);
        String onePassStr = getEditToString(one_pass);

        if(isRequestStr(phoneStr)&&isRequestStr(codeStr)&&isRequestStr(onePassStr)){
            submit.setEnabled(true);
            submit.setBackgroundResource(R.drawable.blue_btn_frame);
        }else{
            submit.setEnabled(false);
            submit.setBackgroundResource(R.drawable.ash_btn_frame);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
